/**
 * Copyright (c) 2022 Beijing Jiaotong University
 * PhotLab is licensed under [Open Source License].
 * You can use this software according to the terms and conditions of the [Open Source License].
 * You may obtain a copy of [Open Source License] at: [https://open.source.license/]
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *
 * See the [Open Source License] for more details.
 *
 * Author: Qing'ao Zhang, Zhenjie Wei
 * Created: Mar. 15, 2023
 * Supported by: National Key Research and Development Program of China
 */

const thrift = require("thrift/lib/nodejs/lib/thrift")

function connection(ip: string | undefined, port: number) {
    console.log("Connecting to " + ip + ":" + port)
    const transport = thrift.TBufferedTransport
    const protocol = thrift.TBinaryProtocol
    const connection = thrift.createConnection(ip, port, {
        transport: transport,
        protocol: protocol
    })

    connection.on("error", function(err: string | Error | undefined) {
        console.error(err)
    })

    console.log("Connected to " + ip + ":" + port)
    return connection
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function thriftClient(service: any, ip: string, port: number) {
    return thrift.createClient(service, connection(ip, port))
}
